import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '../api/auth'

/**
 * 认证状态管理模块
 * 负责用户认证状态的管理，包括登录、注册、退出和用户信息管理
 */

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token'))
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))

  const isAuthenticated = computed(() => !!token.value)
  const currentUser = computed(() => user.value)

  const login = async (username, password) => {
    try {
      const response = await authApi.login(username, password)
      
      token.value = response.access_token
      user.value = {
        id: response.user_id,
        username: response.username
      }
      
      localStorage.setItem('token', token.value)
      localStorage.setItem('user', JSON.stringify(user.value))
      
      message.success('登录成功')
      return true
    } catch (error) {
      message.error('登录失败：' + (error.response?.data?.detail || error.message))
      return false
    }
  }

  const register = async (username, password, email) => {
    try {
      const response = await authApi.register(username, password, email)
      
      token.value = response.access_token
      user.value = {
        id: response.user_id,
        username: response.username
      }
      
      localStorage.setItem('token', token.value)
      localStorage.setItem('user', JSON.stringify(user.value))
      
      message.success('注册成功')
      return true
    } catch (error) {
      message.error('注册失败：' + (error.response?.data?.detail || error.message))
      return false
    }
  }

  const logout = async () => {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('退出登录失败：', error)
    } finally {
      token.value = null
      user.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      message.success('已退出登录')
      
      // 退出后跳转到登录页面
      if (window.location.pathname !== '/login') {
        window.location.href = '/login'
      }
    }
  }

  const checkAuth = async () => {
    if (!token.value) return false
    
    try {
      const response = await authApi.getCurrentUser()
      user.value = response
      return true
    } catch (error) {
      logout()
      return false
    }
  }

  return {
    token,
    user,
    isAuthenticated,
    currentUser,
    login,
    register,
    logout,
    checkAuth
  }
})